<template>
  <a-drawer
    title="课时管理"
    :visible="open"
    :mask-closable="false"
    width="634"
    @close="onCancel"
  >
    <div class="top-content">
      <p>1.线上课课时调整及时生效，操作不可逆，请谨慎操作。</p>
      <p>2.课时调整后，已有学习进度会在学员学习时重新计算。</p>
    </div>
    <div class="float-left mt-24">
      <SelectResource
        :default-keys="chapterType === 0 ? hours : changeChapterHours(chapterHours)"
        :open="videoVisible"
        @cancel="videoVisible = false"
        @selected="handleResourceSelected"
      />
      
      <div v-if="init" class="float-left text-center mt-30">
        <a-spin />
      </div>
      
      <div v-else class="float-left">
        <a-form
          :model="form"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
        >
          <!-- 无章节模式 -->
          <div v-if="chapterType === 0" class="c-flex">
            <a-form-item>
              <div class="ml-42">
                <a-button @click="videoVisible = true" type="primary">
                  添加课时
                </a-button>
              </div>
            </a-form-item>
            <div class="hous-box">
              <span v-if="treeData.length === 0" class="no-hours">
                请点击上方按钮添加课时
              </span>
              <TreeHours
                v-if="treeData.length > 0"
                :data="treeData"
                @remove-item="delHour"
                @update="transHour"
              />
            </div>
          </div>
          
          <!-- 章节模式 -->
          <div v-else class="c-flex">
            <div
              v-for="(item, index) in chapters"
              :key="item.hours.length + '章节' + index"
              class="chapter-item"
            >
              <div class="d-flex">
                <div class="label">章节{{ index + 1 }}：</div>
                <a-input
                  v-model:value="item.name"
                  class="input"
                  placeholder="请在此处输入章节名称"
                  allow-clear
                  @change="(e) => setChapterName(index, e.target.value)"
                  @blur="(e) => saveChapterName(index, e.target.value)"
                />
                <a-button
                  :disabled="!item.name"
                  class="mr-16"
                  type="primary"
                  @click="handleAddChapterHour(index)"
                >
                  添加课时
                </a-button>
                <a-button @click="delChapter(index)">
                  删除章节
                </a-button>
              </div>
              <div class="chapter-hous-box">
                <span v-if="item.hours.length === 0" class="no-hours">
                  请点击上方按钮添加课时
                </span>
                <TreeHours
                  v-if="item.hours.length > 0"
                  :data="item.hours"
                  @remove-item="(id) => delChapterHour(index, id)"
                  @update="(arr) => transChapterHour(index, arr)"
                />
              </div>
            </div>
            
            <a-form-item>
              <div class="ml-42">
                <a-button @click="addNewChapter">
                  添加章节
                </a-button>
              </div>
            </a-form-item>
          </div>
        </a-form>
      </div>
    </div>
  </a-drawer>
</template>

<script setup>
import { ref, watch, reactive, h } from 'vue';
import { Modal, message } from 'ant-design-vue';
import SelectResource from '@/components/Common/select-resource.vue';
import TreeHours from './hours.vue';
import { course, courseHour, courseChapter } from '@/api';
import { ExclamationCircleFilled } from '@ant-design/icons-vue';

const { confirm } = Modal;

const props = defineProps({
  id: {
    type: Number,
    default: 0
  },
  open: {
    type: Boolean,
    default: false
  },
  onCancel: {
    type: Function,
    default: () => {}
  }
});

const emit = defineEmits(['update:open']);

const init = ref(true);
const chapterType = ref(0);
const chapters = ref([]);
const hours = ref([]);
const chapterHours = ref([]);
const videoVisible = ref(false);
const treeData = ref([]);
const addvideoCurrent = ref(0);
const form = reactive({});

// 监听props变化
watch(() => props.open, (newVal) => {
  if (newVal) {
    resetState();
    if (props.id !== 0) {
      getDetail();
    }
  }
});

// 重置状态
const resetState = () => {
  init.value = true;
  videoVisible.value = false;
  chapters.value = [];
  hours.value = [];
  chapterHours.value = [];
  treeData.value = [];
  addvideoCurrent.value = 0;
  chapterType.value = 0;
};

// 获取详情
const getDetail = async () => {
  try {
    const res = await course.course(props.id);
    const hasChapters = res.data.chapters.length > 0;
    chapterType.value = hasChapters ? 1 : 0;
    
    if (hasChapters) {
      treeData.value = [];
      hours.value = [];
      const hoursData = res.data.hours;
      const chaptersData = res.data.chapters;
      const arr = [];
      const keys = [];
      
      for (let i = 0; i < chaptersData.length; i++) {
        const resetResult = resetHours(hoursData[chaptersData[i].id]);
        arr.push({
          id: chaptersData[i].id,
          name: chaptersData[i].name,
          hours: resetResult.arr
        });
        keys.push(resetResult.keys);
      }
      
      chapters.value = arr;
      chapterHours.value = keys;
    } else {
      chapters.value = [];
      chapterHours.value = [];
      const hoursData = res.data.hours;
      
      if (JSON.stringify(hoursData) !== "{}") {
        const resetResult = resetHours(hoursData[0]);
        treeData.value = resetResult.arr;
        hours.value = resetResult.keys;
      } else {
        treeData.value = [];
        hours.value = [];
      }
    }
    
    init.value = false;
  } catch (error) {
    console.error('获取课程详情失败:', error);
    init.value = false;
  }
};

// 重置课时数据
const resetHours = (data) => {
  const arr = [];
  const keys = [];
  
  if (data) {
    for (let i = 0; i < data.length; i++) {
      arr.push({
        duration: data[i].duration,
        type: data[i].type,
        name: data[i].title,
        rid: data[i].rid,
        id: data[i].id
      });
      keys.push(data[i].rid);
    }
  }
  
  return { arr, keys };
};

// 表单提交
const onFinish = (values) => {
  // 处理表单提交逻辑
};

const onFinishFailed = (errorInfo) => {
  console.log("Failed:", errorInfo);
};

// 处理资源选择
const handleResourceSelected = (arr, videos) => {
  if (chapterType.value === 0) {
    selectData(arr, videos);
  } else {
    selectChapterData(arr, videos);
  }
};

// 选择数据（无章节模式）
const selectData = async (arr, videos) => {
  const hoursData = [];
  
  for (let i = 0; i < videos.length; i++) {
    hoursData.push({
      chapter_id: 0,
      sort: treeData.value.length + i,
      title: videos[i].name,
      type: videos[i].type,
      duration: videos[i].duration,
      rid: videos[i].rid
    });
  }
  
  if (hoursData.length === 0) {
    message.error("请选择视频");
    return;
  }
  
  try {
    await courseHour.storeCourseHourMulti(props.id, hoursData);
    message.success("添加成功");
    videoVisible.value = false;
    getDetail();
  } catch (error) {
    console.error("添加课时失败:", error);
  }
};

// 选择章节数据
const selectChapterData = async (arr, videos) => {
  const data = [...chapters.value];
  
  if (!data[addvideoCurrent.value]?.id) {
    message.error("添加课时失败");
    return;
  }
  
  const hoursData = [];
  const currentChapter = data[addvideoCurrent.value];
  
  for (let i = 0; i < videos.length; i++) {
    hoursData.push({
      chapter_id: currentChapter.id,
      sort: currentChapter.hours.length + i,
      title: videos[i].name,
      type: videos[i].type,
      duration: videos[i].duration,
      rid: videos[i].rid
    });
  }
  
  if (hoursData.length === 0) {
    message.error("请选择视频");
    return;
  }
  
  try {
    await courseHour.storeCourseHourMulti(props.id, hoursData);
    message.success("添加成功");
    videoVisible.value = false;
    getDetail();
  } catch (error) {
    console.error("添加课时失败:", error);
  }
};

// 删除课时（无章节模式）
const delHour = (hid) => {
  const data = [...treeData.value];
  const index = data.findIndex(i => i.rid === hid);
  
  if (index === -1) return;
  
  confirm({
    title: "操作确认",
    icon: () => h(ExclamationCircleFilled),
    content: "确认删除此课时？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      const delId = data[index].id;
      
      if (index >= 0) {
        data.splice(index, 1);
      }
      
      if (data.length > 0) {
        treeData.value = data;
        hours.value = data.map(item => item.rid);
      } else {
        treeData.value = [];
        hours.value = [];
      }
      
      if (delId) {
        try {
          await courseHour.destroyCourseHour(props.id, delId);
          message.success("删除成功");
        } catch (error) {
          console.error("删除课时失败:", error);
        }
      }
    }
  });
};

// 调整课时顺序（无章节模式）
const transHour = async (arr) => {
  hours.value = arr;
  const data = [...treeData.value];
  const newArr = [];
  const hourIds = [];
  
  for (let i = 0; i < arr.length; i++) {
    const item = data.find(item => item.rid === arr[i]);
    if (item) {
      newArr.push(item);
      hourIds.push(item.id);
    }
  }
  
  treeData.value = newArr;
  
  try {
    await courseHour.transCourseHour(props.id, hourIds);
  } catch (error) {
    console.error("调整课时顺序失败:", error);
  }
};

// 添加新章节
const addNewChapter = () => {
  const arr = [...chapters.value];
  const keys = [...chapterHours.value];
  
  arr.push({
    name: "",
    hours: []
  });
  keys.push([]);
  
  chapters.value = arr;
  chapterHours.value = keys;
};

// 设置章节名称
const setChapterName = (index, value) => {
  const arr = [...chapters.value];
  arr[index].name = value;
  chapters.value = arr;
};

// 保存章节名称
const saveChapterName = async (index, value) => {
  const arr = [...chapters.value];
  
  if (!value.trim()) {
    message.warning("章节名称不能为空");
    return;
  }
  
  try {
    if (arr[index].id) {
      await courseChapter.updateCourseChapter(props.id, Number(arr[index].id), value, index + 1);
    } else {
      await courseChapter.storeCourseChapter(props.id, value, arr.length);
    }
    message.success("保存成功");
    getDetail();
  } catch (error) {
    console.error("保存章节名称失败:", error);
  }
};

// 删除章节
const delChapter = (index) => {
  const arr = [...chapters.value];
  
  confirm({
    title: "操作确认",
    icon: () => h(ExclamationCircleFilled),
    content: "删除章节会清空已添加课时，确认删除？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      if (arr[index].id) {
        try {
          await courseChapter.destroyCourseChapter(props.id, Number(arr[index].id));
          message.success("删除成功");
          getDetail();
        } catch (error) {
          console.error("删除章节失败:", error);
        }
      }
    }
  });
};

// 删除章节课时
const delChapterHour = (index, hid) => {
  const keys = [...chapterHours.value];
  const data = [...chapters.value];
  const currentChapter = data[index];
  
  const currentIndex = currentChapter.hours.findIndex(i => i.rid === hid);
  
  if (currentIndex === -1) return;
  
  confirm({
    title: "操作确认",
    icon: () => h(ExclamationCircleFilled),
    content: "确认删除此课时？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      const delId = currentChapter.hours[currentIndex].id;
      
      if (currentIndex >= 0) {
        currentChapter.hours.splice(currentIndex, 1);
      }
      
      if (currentChapter.hours.length > 0) {
        chapters.value = data;
        keys[index] = currentChapter.hours.map(item => item.rid);
        chapterHours.value = keys;
      } else {
        keys[index] = [];
        currentChapter.hours = [];
        chapters.value = data;
        chapterHours.value = keys;
      }
      
      if (delId) {
        try {
          await courseHour.destroyCourseHour(props.id, delId);
          message.success("删除成功");
        } catch (error) {
          console.error("删除课时失败:", error);
        }
      }
    }
  });
};

// 调整章节课时顺序
const transChapterHour = async (index, arr) => {
  const keys = [...chapterHours.value];
  keys[index] = arr;
  chapterHours.value = keys;
  
  const data = [...chapters.value];
  const currentChapter = data[index];
  const newArr = [];
  const hourIds = [];
  
  for (let i = 0; i < arr.length; i++) {
    const item = currentChapter.hours.find(item => item.rid === arr[i]);
    if (item) {
      newArr.push(item);
      hourIds.push(item.id);
    }
  }
  
  currentChapter.hours = newArr;
  chapters.value = data;
  
  try {
    await courseHour.transCourseHour(props.id, hourIds);
  } catch (error) {
    console.error("调整课时顺序失败:", error);
  }
};

// 转换章节课时数据
const changeChapterHours = (arr) => {
  const newArr = [];
  for (let i = 0; i < arr.length; i++) {
    newArr.push(...arr[i]);
  }
  return newArr;
};

// 处理添加章节课时
const handleAddChapterHour = (index) => {
  const data = [...chapters.value];
  if (!data[index].name) {
    message.warning("请先输入章节名称");
    return;
  }
  setAddvideoCurrent(index);
  videoVisible.value = true;
};

// 设置当前添加视频的章节索引
const setAddvideoCurrent = (index) => {
  addvideoCurrent.value = index;
};
</script>

<style scoped>
.top-content {
  width: 502px;
  height: auto;
  background: rgba(255, 77, 79, 0.1);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-sizing: border-box;
  padding: 8px 16px;
  margin: 0 auto;
}

.top-content p {
  font-size: 14px;
  font-weight: 400;
  color: #ff4d4f;
  line-height: 24px;
  margin: 0;
}

.hous-box {
  width: 500.53px;
  min-height: 56px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  box-sizing: border-box;
  padding: 8px 8px 0px 8px;
  margin-left: 42px;
  display: flex;
  flex-direction: column;
}

.hous-box .no-hours {
  height: 24px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.25);
  line-height: 24px;
  margin-top: 8px;
}

.chapter-item {
  width: 502px;
  height: auto;
  display: flex;
  flex-direction: column;
  margin-left: 42px;
  margin-bottom: 16px;
}

.chapter-item .label {
  width: 78px;
  height: 32px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 32px;
}

.chapter-item .input {
  width: 208px;
  height: 32px;
  margin-right: 24px;
}

.chapter-item .chapter-hous-box {
  width: 500.53px;
  min-height: 56px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  box-sizing: border-box;
  padding: 8px 8px 0px 8px;
  margin-top: 16px;
  display: flex;
  flex-direction: column;
}

.chapter-item .chapter-hous-box .no-hours {
  height: 24px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.25);
  line-height: 24px;
  margin-top: 8px;
}

.ml-42 {
  margin-left: 42px;
}

.mt-24 {
  margin-top: 24px;
}

.mt-30 {
  margin-top: 30px;
}

.mr-16 {
  margin-right: 16px;
}

.float-left {
  float: left;
}

.text-center {
  text-align: center;
}

.d-flex {
  display: flex;
}

.c-flex {
  display: flex;
  flex-direction: column;
}
</style>